
/*
 * Copyright 2002-2023 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 *版权所有2002-2023原作者。
 *
 *根据Apache许可证2.0版（“许可证”）许可；
 *除非符合许可证的规定，否则您不得使用此文件。
 *您可以在以下网址获取许可证副本
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 *除非适用法律要求或书面同意，否则软件
 *根据许可证分发是在“按原样”的基础上分发的，
 *无任何明示或暗示的保证或条件。
 *有关管理权限的特定语言，请参阅许可证
 *许可证下的限制。
 */

package org.springframework.context.support;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationContextException;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

/**
 * Convenient superclass for application objects that want to be aware of
 * the application context, e.g. for custom lookup of collaborating beans
 * or for context-specific resource access. It saves the application
 * context reference and provides an initialization callback method.
 * Furthermore, it offers numerous convenience methods for message lookup.
 *
 * <p>There is no requirement to subclass this class: It just makes things
 * a little easier if you need access to the context, e.g. for access to
 * file resources or to the message source. Note that many application
 * objects do not need to be aware of the application context at all,
 * as they can receive collaborating beans via bean references.
 *
 * <p>Many framework classes are derived from this class, particularly
 * within the web support.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @see org.springframework.web.context.support.WebApplicationObjectSupport
 */
/**
 *用于希望了解的应用程序对象的方便的超类
 *应用程序上下文，例如用于协作bean的自定义查找
 *或者用于上下文特定的资源访问。它保存应用程序
 *上下文引用，并提供初始化回调方法。
 *此外，它还提供了许多方便的消息查找方法。
 *
 *＜p＞不需要对这个类进行子类化：它只是生成一些东西
 *如果您需要访问上下文，例如访问
 *文件资源或消息源。请注意，许多应用程序
 *对象根本不需要知道应用程序上下文，
 *因为他们可以通过bean引用接收协作bean。
 *
 *<p>许多框架类都是从这个类派生的，特别是
 *在web支持中。
 *
 *@作者罗德·约翰逊
 *@作者Juergen Hoeller
 *@请参阅org.springframework.web.context.support.WebApplicationObjectSupport
 */
public abstract class ApplicationObjectSupport implements ApplicationContextAware {

	/** Logger that is available to subclasses. */
	protected final Log logger = LogFactory.getLog(getClass());

	/** ApplicationContext this object runs in. */
	@Nullable
	private ApplicationContext applicationContext;

	/** MessageSourceAccessor for easy message access. */
	@Nullable
	private MessageSourceAccessor messageSourceAccessor;


	@Override
	public final void setApplicationContext(@Nullable ApplicationContext context) throws BeansException {
		if (context == null && !isContextRequired()) {
			// Reset internal context state.
			// 重置内部上下文状态。
			this.applicationContext = null;
			this.messageSourceAccessor = null;
		}
		else if (this.applicationContext == null) {
			// Initialize with passed-in context.
			// 使用传入的上下文初始化。
			if (!requiredContextClass().isInstance(context)) {
				throw new ApplicationContextException(
						"Invalid application context: needs to be of type [" + requiredContextClass().getName() + "]");
			}
			this.applicationContext = context;
			this.messageSourceAccessor = new MessageSourceAccessor(context);
			initApplicationContext(context);
		}
		else {
			// Ignore reinitialization if same context passed in.
			// 若传入了相同的上下文，则忽略重新初始化。
			if (this.applicationContext != context) {
				throw new ApplicationContextException(
						"Cannot reinitialize with different application context: current one is [" +
						this.applicationContext + "], passed-in one is [" + context + "]");
			}
		}
	}

	/**
	 * Determine whether this application object needs to run in an ApplicationContext.
	 * <p>Default is "false". Can be overridden to enforce running in a context
	 * (i.e. to throw IllegalStateException on accessors if outside a context).
	 * @see #getApplicationContext
	 * @see #getMessageSourceAccessor
	 */
	/** Logger that is available to subclasses. */
	受保护的最终日志记录器=LogFactory.getLog（getClass（））；

	/**此对象在其中运行的ApplicationContext*/
	@可为null
	private应用程序上下文应用程序上下文；

	/**MessageSourceAccessor可轻松访问消息*/
	@可为null
	private MessageSourceAccessor MessageSourceAccessor；


	@覆盖
	public最终void setApplicationContext（@Nullable ApplicationContext上下文）抛出BeansException{
		if（context==null&&！isContextRequired（））{
			this.applicationContext=空；
			this.messageSourceAccessor=null；
		}
		否则如果（this.applicationContext==null）{
			if（！requiredContextClass（）.isIInstance（context））{
				引发新的ApplicationContextException(
						“无效的应用程序上下文：需要为[”+requiredContextClass（）.getName（）+“]”）类型；
			}
			this.applicationContext=上下文；
			this.messageSourceAccessor=新的messageSourceAccessor（上下文）；
			initApplicationContext（上下文）；
		}
		其他{
			if（this.applicationContext！=上下文）{
				引发新的ApplicationContextException(
						“无法使用不同的应用程序上下文重新初始化：当前应用程序上下文为[”+
						this.applicationContext+“]，传入一个是[”+context+“]“）；
			}
		}
	}

	/**
	 *确定此应用程序对象是否需要在ApplicationContext中运行。
	 *<p>默认值为“false”。可以重写以强制在上下文中运行
	 *（即，如果在上下文之外，则对访问者抛出IllegalStateException）。
	 *@参见#getApplicationContext
	 *@参见#getMessageSourceAccessor
	 */
	protected boolean isContextRequired() {
		return false;
	}

	/**
	 * Determine the context class that any context passed to
	 * {@code setApplicationContext} must be an instance of.
	 * Can be overridden in subclasses.
	 * @see #setApplicationContext
	 */
	/**
	 *确定任何上下文传递到的上下文类
	 *｛@code setApplicationContext｝必须是的实例。
	 *可以在子类中重写。
	 *@参见#setApplicationContext
	 */
	protected Class<?> requiredContextClass() {
		return ApplicationContext.class;
	}

	/**
	 * Subclasses can override this for custom initialization behavior.
	 * Gets called by {@code setApplicationContext} after setting the context instance.
	 * <p>Note: Does <i>not</i> get called on re-initialization of the context
	 * but rather just on first initialization of this object's context reference.
	 * <p>The default implementation calls the overloaded {@link #initApplicationContext()}
	 * method without ApplicationContext reference.
	 * @param context the containing ApplicationContext
	 * @throws ApplicationContextException in case of initialization errors
	 * @throws BeansException if thrown by ApplicationContext methods
	 * @see #setApplicationContext
	 */
	/**
	 *子类可以为自定义初始化行为覆盖此项。
	 *设置上下文实例后由｛@code setApplicationContext｝调用。
	 *<p>注意：在重新初始化上下文时是否调用<i>而不调用</i>
	 *而是仅在该对象的上下文引用的第一次初始化时。
	 *＜p＞默认实现调用重载的｛@link#initApplicationContext（）｝
	 *方法，但没有ApplicationContext引用。
	 *@param context包含的ApplicationContext
	 *在初始化错误的情况下@throws ApplicationContextException
	 *@throws BeansException如果由ApplicationContext方法引发
	 *@参见#setApplicationContext
	 */
	protected void initApplicationContext(ApplicationContext context) throws BeansException {
		initApplicationContext();
	}

	/**
	 * Subclasses can override this for custom initialization behavior.
	 * <p>The default implementation is empty. Called by
	 * {@link #initApplicationContext(ApplicationContext)}.
	 * @throws ApplicationContextException in case of initialization errors
	 * @throws BeansException if thrown by ApplicationContext methods
	 * @see #setApplicationContext
	 */
	/**
	 *子类可以为自定义初始化行为覆盖此项。
	 *＜p＞默认实现为空。呼叫方
	 *｛@link#initApplicationContext（ApplicationContext）｝。
	 *在初始化错误的情况下@throws ApplicationContextException
	 *@throws BeansException如果由ApplicationContext方法引发
	 *@参见#setApplicationContext
	 */
	protected void initApplicationContext() throws BeansException {
	}


	/**
	 * Return the ApplicationContext that this object is associated with.
	 * @throws IllegalStateException if not running in an ApplicationContext
	 */
	/**
	 *返回与此对象关联的ApplicationContext。
	 *如果没有在ApplicationContext中运行，则@throws IllegalStateException
	 */
	@Nullable
	public final ApplicationContext getApplicationContext() throws IllegalStateException {
		if (this.applicationContext == null && isContextRequired()) {
			throw new IllegalStateException(
					"ApplicationObjectSupport instance [" + this + "] does not run in an ApplicationContext");
		}
		return this.applicationContext;
	}

	/**
	 * Obtain the ApplicationContext for actual use.
	 * @return the ApplicationContext (never {@code null})
	 * @throws IllegalStateException in case of no ApplicationContext set
	 * @since 5.0
	 */
	/**
	 *获取ApplicationContext以供实际使用。
	 *@return ApplicationContext（从不｛@code null｝）
	 *在没有设置ApplicationContext的情况下@throws IllegalStateException
	 *@自5.0起
	 */
	protected final ApplicationContext obtainApplicationContext() {
		ApplicationContext applicationContext = getApplicationContext();
		Assert.state(applicationContext != null, "No ApplicationContext");
		return applicationContext;
	}

	/**
	 * Return a MessageSourceAccessor for the application context
	 * used by this object, for easy message access.
	 * @throws IllegalStateException if not running in an ApplicationContext
	 */
	/**
	 *返回应用程序上下文的MessageSourceAccessor
	 *由该对象使用，以便轻松访问消息。
	 *如果没有在ApplicationContext中运行，则@throws IllegalStateException
	 */
	@Nullable
	protected final MessageSourceAccessor getMessageSourceAccessor() throws IllegalStateException {
		if (this.messageSourceAccessor == null && isContextRequired()) {
			throw new IllegalStateException(
					"ApplicationObjectSupport instance [" + this + "] does not run in an ApplicationContext");
		}
		return this.messageSourceAccessor;
	}

}
